import {login, logout, getInfo} from '@/api/user'
import {getToken, setToken, removeToken} from '@/utils/auth'
import router, {resetRouter} from '@/router'

const state = {
  clinicId: '',
  phone: '',
  // token: getToken(),
  roles: [],
  staff: {},
  treeMenu: [],
  userMenu: [],
  token: '',
  name: '',
  avatar: '',
  introduction: '',
  siderType: true,
  reports: [],
  selectedPatientInfo: {}, // 选中的患者信息
  medicalRecordSaved: false, // 添加病历保存状态
  signInInfo: {},//医保签到信息
}

const mutations = {
  SET_CLINICID: (state, clinicId) => {
    state.clinicId = clinicId
  },
  SET_PHONE: (state, phone) => {
    state.phone = phone
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  },
  SET_STAFF: (state, staff) => {
    state.staff = staff
  },
  SET_TREE_MENU: (state, treeMenu) => {
    state.treeMenu = treeMenu
  },
  SET_USERMENU: (state, userMenu) => {
    state.userMenu = userMenu
  },
  SET_INTRODUCTION: (state, introduction) => {
    state.introduction = introduction
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  CHANGE_SIDER_TYPE: (state) => {
    state.siderType = !state.siderType
  },
  SET_REPORTS: (state, treeMenu) => {
    state.reports = treeMenu
  },
  SET_SELECTED_PATIENT_INFO: (state, selectedPatientInfo) => {
    state.selectedPatientInfo = selectedPatientInfo
  },
  SET_MEDICAL_RECORD_STATUS(state, status) {
    state.medicalRecordSaved = status
  },
  SET_SIGNININFO: (state, signInInfo) => {
    state.signInInfo = signInInfo
  },
}

const actions = {
  login({commit}, userInfo) {
    const {username, password} = userInfo
    // return new Promise((resolve, reject) => {
    return login({phone: username.trim(), userPw: password}).then(response => {
      // const { body } = response
      // commit('SET_TOKEN', body.authorization)
      // setToken(body.authorization)

      const {data} = response
      // console.log(data)
      commit('SET_CLINICID', data.staff.id)
      commit('SET_PHONE', data.staff.phone)
      // commit('SET_TOKEN', data.token)
      // setToken(data.token)
      // resolve(data)
      return data
    }).catch(error => {
      console.log(error)
      reject(error)
    })
    // })
  },

  // get user info
  getInfo1({commit, state}) {
    console.log('getinfo', state.token)
    const roles = ['admin']
    const name = 'name'
    const avatar = 'https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif'
    const introduction = '我是管理者'
    commit('SET_ROLES', roles)
    commit('SET_NAME', name)
    commit('SET_AVATAR', avatar)
    commit('SET_INTRODUCTION', introduction)
  },
  getInfo({commit, state}) {
    return new Promise((resolve, reject) => {
      // 怎么把clinicId和phone传给后台
      console.log('getinfo', state.clinicId, state.phone)
      const clinicId = state.clinicId
      const phone = state.phone
      getInfo({clinicId, phone}).then(response => {
        const {data} = response

        if (!data) {
          reject('Verification failed, please Login again.')
        }

        const {roles, name, avatar, introduction} = data

        // roles must be a non-empty array
        if (!roles || roles.length <= 0) {
          reject('getInfo: roles must be a non-null array!')
        }

        commit('SET_ROLES', roles)
        commit('SET_NAME', name)
        commit('SET_AVATAR', avatar)
        commit('SET_INTRODUCTION', introduction)
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({commit, state, dispatch}) {
    return new Promise((resolve, reject) => {
      sessionStorage.clear()
      commit('SET_TOKEN', '')
      router.replace({path: '/login'})
    }).catch(error => {
      reject(error)
    })
    // return new Promise((resolve, reject) => {
    //   logout(state.token).then(() => {
    //     commit('SET_TOKEN', '')
    //     commit('SET_ROLES', [])
    //     sessionStorage.clear()
    //     router.replace({path: '/login'})
    //     removeToken()
    //     resetRouter()
    //     // dispatch('tagsView/delAllViews', null, {root: true})
    //
    //     resolve()
    //   }).catch(error => {
    //     reject(error)
    //   })
    // })
  },

  // remove token
  resetToken({commit}) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      commit('SET_ROLES', [])
      removeToken()
      resolve()
    })
  },

  // dynamically modify permissions
  async changeRoles({commit, dispatch}, role) {
    const token = role + '-token'

    commit('SET_TOKEN', token)
    setToken(token)

    const {roles} = await dispatch('getInfo')

    resetRouter()

    // generate accessible routes map based on roles
    const accessRoutes = await dispatch('permission/generateRoutes', roles, {root: true})
    // dynamically add accessible routes
    router.addRoutes(accessRoutes)

    // reset visited views and cached views
    dispatch('tagsView/delAllViews', null, {root: true})
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
